<?php

namespace App\Api\V1\Controllers;

use App\Models\Behavior;
use App\Models\Behavior\Cat;
use App\Models\Points;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Exceptions\JWTException;

class BehaviorController extends Controller
{
    protected $guard = 'api';

    /**
     * 获取行为分类
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBehaviorCat()
    {
        $data = Cat::select(['id as type', 'name'])->orderBy('sort', 'asc')->get();

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    public function getBehaviors()
    {
        $data = Behavior::getBehaviors();

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 根据行为分类获取行为
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBehaviorByCat(Request $request)
    {
        $this->validate($request, [
            'cat_id' => 'required',
            'type'   => 'required',
        ]);

        $data = Behavior::getBehaviorByCat($request->cat_id, $request->type);

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 评价打分 生成记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addBehaviorRecord(Request $request)
    {
        $this->validate($request, [
            'user_id'     => 'required',
            'behavior_id' => 'required',
        ]);

        $user_id     = $request->user_id;
        $behavior_id = $request->behavior_id;

        $record_user = Auth::guard($this->guard)->user();

        //不能给自己打分
        if ($record_user['id'] == $user_id)
            return response()->json([
                'status_code' => 0,
                'message'     => '不能给自己打分',
            ]);

        $user = User::find($user_id);
        if (!$user)
            return response()->json([
                'status_code' => 0,
                'message'     => '用户不存在',
            ]);

        $behavior = Behavior::find($behavior_id);
        if (!$behavior)
            return response()->json([
                'status_code' => 0,
                'message'     => '您选择的行为不存在',
            ]);



        $score = $behavior->type == 1 ? $behavior->score : $behavior->score * (-1);

        //积分设置
        $setting = Points\Setting::first();
        if ($setting) {
            $points_initial   = $setting['points_initial'];//初始值
            $points_day_top   = $setting['points_day_top'];//单日封顶值
            $points_total_top = $setting['points_total_top'];//总封顶值

            $user_points = Points::where('user_id', $user_id)->first();
            if (!$user_points && $points_initial) {
                $points = new Points;
                $points->user_id = $user_id;
                $points->init_points = $points_initial;
                $points->save();
            }

            //总封顶 ==0表示不封顶
            if ($points_total_top > 0) {
                $points = $user_points->points ? $user_points->points : 0;
                if ($points >= $points_total_top) {
                    return response()->json([
                        'status_code' => 0,
                        'message'     => '记录失败,积分已超过总封顶值',
                        'data'        => []
                    ]);
                }
            }

            //单日封顶 ==0表示不封顶
            if ($points_day_top > 0) {
                $time = get_time(1);

                $record_score = Behavior\Record::where('created_at', '>=', $time['start_time'])
                    ->where('created_at', '<=', $time['end_time'])
                    ->sum('score');

                if ($record_score >= $points_day_top) {
                    return response()->json([
                        'status_code' => 0,
                        'message'     => '记录失败,积分已超过单日封顶值',
                        'data'        => $record_score
                    ]);
                }

            }
        }



        $record = new Behavior\Record();

        $record->user_id           = $user_id;
        $record->behavior_id       = $behavior_id;
        $record->behavior_name     = $behavior->name;
        $record->behavior_type     = $behavior->type;
        $record->score             = $score;
        $record->behavior_image_id = $behavior->image_id;
        $record->record_user_id    = $record_user['id'];

        $flag = $record->save();

        if ($flag) {
            $user_points = Points::where('user_id', $user_id)->first();

            if ($user_points) {
                $user_points->points = $user_points->points + $score;
                if ($behavior->type == 1) {
                    $user_points->positive_points += $behavior->score;
                } else {
                    $user_points->negative_points += $behavior->score;
                }
                $user_points->update();

            } else {
                $points_initial = 0;

                $setting = Points\Setting::first();
                if ($setting){
                    $points_initial += $setting['points_initial'];
                }
                $points = new Points;
                $points->user_id = $user_id;
                $points->points = $score;
                $points->init_points = $points_initial;

                $points->save();
            }
        }

        if ($flag)
            return response()->json([
                'status_code' => 1,
                'message'     => '记录成功',
            ]);
        else
            return response()->json([
                'status_code' => 0,
                'message'     => '记录失败',
            ]);


    }

    /**
     * 删除记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function removeBehaviorRecord(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
        ]);

        $record = Behavior\Record::find($request->id);

        if ($record) {
            $user_id = $record->user_id;
            $user_points = Points::where('user_id', $user_id)->first();

            $user_points->points -= $record->score;
            $user_points->update();
            $record->delete();

        } else {
            return response()->json([
                'status_code' => 0,
                'message'     => '删除失败',
            ]);
        }

    }

    /**
     * 获取评分记录
     *
     * @param Request $request user_id date_type page
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBehaviorRecords(Request $request)
    {
        $this->validate($request, [
            'user_id'     => 'required',
        ]);

        $record_data = Behavior\Record::getBehaviorRecords($request->user_id, $request->date_type);

        $data = [];
        if ($record_data) {
            $data['current_page'] = $record_data['current_page'];
            $data['total_page'] = $record_data['last_page'];
            $data['data'] = $record_data['data'];
        }

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);


    }

    /**
     * 获取最新10条记录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNewBehaviorRecords()
    {
        $record_data = Behavior\Record::getNewBehaviorRecords();

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $record_data
        ]);
    }

    /**
     * 获取排行榜记录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBehaviorRange()
    {
        //$record_data = Behavior\Record::getBehaviorRange();

        $row = User::leftJoin('love_points as b','love_users.id','b.user_id')
            ->leftJoin('love_family_users as c', 'love_users.id', 'c.user_id')
            ->selectRaw(
                'love_users.id,love_users.username,love_users.avatar,love_users.mobile,(b.points + b.init_points) as total_points,b.points,b.positive_points,b.negative_points,b.init_points,c.is_householder'
            )
            ->orderBy('total_points', 'desc')
            ->orderBy('love_users.id','asc')
            ->paginate(10)->toArray();

        $data = [];
        if ($row) {
            $data['current_page'] = $row['current_page'];
            $data['total_page'] = $row['last_page'];
            $data['data'] = $row['data'];
        }

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 获取我的点评
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMyBehaviorRecords()
    {
        $user = Auth::guard($this->guard)->user();
        if (!$user)
            return response()->json([
                'status_code' => 0,
                'message'     => 'fail',
            ]);

        $data = Behavior\Record::getMyBehaviorRecords($user['id']);

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 获取全部点评
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllBehaviorRecords()
    {
        $data = Behavior\Record::getAllBehaviorRecords();

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 获取点评
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRecords(Request $request)
    {
        $this->validate($request, [
            'type'     => 'required',
        ]);

        if ($request->type == 1) {
            $user = Auth::guard($this->guard)->user();
            if (!$user)
                return response()->json([
                    'status_code' => 0,
                    'message'     => 'fail',
                ]);

            $data = Behavior\Record::getRecords($user['id']);
        } else {
            $data = Behavior\Record::getRecords();
        }

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 根据user_id 获取个人记录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRecordsByUserId(Request $request)
    {
        $this->validate($request, [
            'user_id'     => 'required',
        ]);

        $data = Behavior\Record::getRecordsByUserId($request->user_id);

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 获取行为图标
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBehaviorImages()
    {
        $data = Behavior\Image::select(['id','name','url'])->get();

        return response()->json([
            'status_code' => 1,
            'message'     => 'success',
            'data'        => $data
        ]);
    }

    /**
     * 添加行为
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addBehavior(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'type' => 'required',
            'cat_id' => 'required',
            'image_id' => 'required',
            'score' => 'required|min:1'
        ]);

        if (!in_array($request->type, [1,2]))
            return response()->json([
                'status_code' => 0,
                'message'     => '类型不正确',
            ]);

        $behavior = new Behavior();
        $behavior->name = $request->name;
        $behavior->type = $request->type;
        $behavior->cat_id = $request->cat_id;
        $behavior->image_id = $request->image_id;
        $behavior->score = $request->score;

        $flag = $behavior->save();

        if ($flag)
            return response()->json([
                'status_code' => 1,
                'message'     => '添加成功',
            ]);
        else
            return response()->json([
                'status_code' => 0,
                'message'     => '添加失败',
            ]);
    }

    /**
     * 删除行为
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function removeBehavior(Request $request)
    {
        $this->validate($request, [
            'behavior_id' => 'required',
        ]);

        $flag = Behavior::where('id', $request->behavior_id)->delete();

        if ($flag)
            return response()->json([
                'status_code' => 1,
                'message'     => '删除成功',
            ]);
        else
            return response()->json([
                'status_code' => 0,
                'message'     => '删除失败',
            ]);
    }

    public function editBehavior(Request $request)
    {
        $this->validate($request, [
            'behavior_id' => 'required',
        ]);

        $name = $request->name;
        $type = $request->type;
        $cat_id = $request->cat_id;
        $image_id = $request->image_id;
        $score = $request->score;

        if ($name || $type || $cat_id || $image_id || $score) {
            $behavior = Behavior::find($request->behavior_id);
            if ($behavior) {
                if ($name)
                    $behavior->name = $name;

                if ($type) {
                    if (in_array($type,[1,2]))
                        $behavior->type = $type;
                    else
                        return response()->json([
                            'status_code' => 0,
                            'message'     => '类型值错误',
                        ]);
                }

                if ($cat_id)
                    $behavior->cat_id = $cat_id;

                if ($image_id)
                    $behavior->image_id = $image_id;

                if ($score)
                    $behavior->score = $score;

                $flag = $behavior->save();
                if ($flag) {
                    $status_code = 1;
                    $message = '修改成功';
                } else {
                    $status_code = 0;
                    $message = '修改失败';
                }

            } else {
                $status_code = 0;
                $message = '行为不存在';
            }


        } else {
            $status_code = 0;
            $message = '参数错误';
        }

        return response()->json([
            'status_code' => $status_code,
            'message'     => $message,
        ]);
    }

}
